/**
 * 对微信小程序 wx.request 文件接口进行封装，
 * 支持 promise
 */

import { error, defaultValUndefined, checkUndefined } from './utils'

//添加事件结束
Promise.prototype.finally = function(callback) {
  var Promise = this.constructor
  return this.then(
    function(value) {
      Promise.resolve(callback()).then(function() {
        return value
      })
    },
    function(reason) {
      Promise.resolve(callback()).then(function() {
        throw reason
      })
    }
  )
}

const app = getApp()

// 响应拦截器 res -> 后端数据业务(不是微信的响应)
const resInterceptor = function(res) {
  // code = 1 表示业务数据调用成功,可以根据业务需要进行设置
  if (res.code == 0) {
    error(res.data)
    return false
  }
  return true
}

const request = function(req) {
  return new Promise(function(resolve, reject) {
    wx.request({
      url: checkUndefined(req.url),
      data: defaultValUndefined(req.data, ''),
      header: defaultValUndefined(req.header, {
        'Content-Type': 'application/json',
        Authorization: defaultValUndefined(app.globalData.token, '')
      }),
      method: defaultValUndefined(req.method, 'GET'),
      dataType: defaultValUndefined(req.dataType, 'json'),
      responseType: defaultValUndefined(req.responseType, 'text'),
      success: function(res) {
        // 拦截请求，进行业务错误码判断
        if (res.statusCode == 200 && resInterceptor(res.data)) {
          resolve(res.data)
        }
      },
      fail: function(res) {
        reject({ error: '网络异常...' })
      },
      complete: function(res) {}
    })
  })
}

export default request
